<%// Copyright 2008 Carnegie Mellon University
  // Licensed under the Apache License, Version 2.0 (the "License"); 
  // you may not use this file except in compliance with the License.
  // You may obtain a copy of the License at
  //  
  //   http://www.apache.org/licenses/LICENSE-2.0
  //
  // Unless required by applicable law or agreed to in writing, 
  // software distributed under the License is distributed on an
  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  // KIND, either express or implied. See the License for the
  // specific language governing permissions and limitations
  // under the License.%>

<%@page language="java" contentType="text/html; charset=UTF-8" %>
<%@page pageEncoding="UTF-8" %>
<%@page import="java.sql.*,java.util.*"%>
<%@page import="edu.cmu.lti.sepia.data.db.*"%>
<%@page import="edu.cmu.lti.sepia.data.resource.ResourceManager"%>
<%@page import="edu.cmu.lti.sepia.infra.topic.model.Task"%>
<%@page import="edu.cmu.lti.sepia.infra.system.model.User"%>
<%@page import="edu.cmu.lti.sepia.infra.system.model.Permission"%>
<%@page import="edu.cmu.lti.sepia.servlet.Commons"%>

<%!
private String generateSelect(User user, Task task, 
        Map<String, Integer> pMap, Map<Integer, String> privLabels ) {
  if ( user.getRole().equalsIgnoreCase("admin") ) {
    return "admin";
  }
  Integer priv = pMap.get(user.getUserId() + "." + task.getTaskId());
  String role = (priv != null ? privLabels.get(priv) : "-");
  StringBuilder sb = new StringBuilder();
  sb.append("<select onchange=\"addPermission("+user.getUserId()+","+task.getTaskId()+",this)\">");
  sb.append("<option value=\"10\" "+(role.equals("-")?"selected":"")+">-</option>");  
  sb.append("<option value=\"20\" "+(role.equals("participant")?"selected":"")+">participant</option>");
  sb.append("<option value=\"30\" "+(role.equals("assessor")?"selected":"")+">assessor</option>");
  sb.append("<option value=\"40\" "+(role.equals("organizer")?"selected":"")+">organizer</option>");
  sb.append("</select>");
  return sb.toString();
}
%>

<%
  out.println(Commons.getHeader(request, response, "Permission Table", 1));
  
  Map<Integer, String> privLabels = new HashMap<Integer, String>();
  privLabels.put(0, "guest");//not implemented yet
  privLabels.put(10, "-");
  privLabels.put(20, "participant");
  privLabels.put(30, "assessor");
  privLabels.put(40, "organizer");
%>

<input id="permissions" type="text" value="" style="display:none">
<script type="text/javascript">
function addPermission(uid, tid, obj) {
  var cur = document.getElementById('permissions').value;
  cur += (cur?",":"")+uid+"."+tid+"."+obj[obj.selectedIndex].value;
  document.getElementById('permissions').value = cur;
}

function save() {
  var param = [];
  param.action      = "UpdatePermissions";
  param.permissions = $('permissions').value;
  sync(param);
  log("UPDATE PERMISSIONS",'');
  showMessage( msg_suc_updated );
}
</script>

<%
  SQL sql = new SQL();
  List<Task> tasks = TaskDAO.getTasks(sql);
  List<User> users = UserDAO.getUsers(sql);
  List<Permission> permissions = PermissionDAO.getPermissions(sql);
  sql.close();

  Map<String, Integer> pMap = new HashMap<String, Integer>();
  for (Permission p : permissions) {
    pMap.put(p.getUserId() + "." + p.getTaskId(), p.getPrivilege());
  }
    
  //sort user
  Collections.sort(users, new Comparator<User>() {
    public int compare(User u1, User u2) {
      int val1 = u1.getUserId();
      int val2 = u2.getUserId();
      int diff = val1 - val2;
      if (diff > 0) {
        return +1;
      } else if (diff < 0) {
        return -1;
      } else {
        return 0;
      }
    }
  });
%>

<%!String printHeader(List<Task> tasks) {
    StringBuilder sb = new StringBuilder();
    sb.append("<tr>\n");
    sb.append("<th valign=\"bottom\">User name</th>\n");
    sb.append("<th valign=\"bottom\">Description</th>\n");
    for (Task task : tasks) {
      sb.append("<th align=\"center\">" + task.getFullName() + "</th>\n");
    }
    sb.append("</tr>\n");
    return sb.toString();
  }%>

<table cellpadding="0" cellspacing="0" border="0" class="datatable">
<thead>
<%=printHeader(tasks)%>
</thead>
<tbody>
<%
  {
    StringBuilder sb = new StringBuilder();
    int counter = 0;
    for (User user : users) {
      //if (user.getUserName().matches("admin|manager"))
      //  continue;
      sb.append("<tr class=\"" + (counter++ % 2 == 1 ? "odd" : "even") + "\">");
      sb.append("<td nowrap>" + user.getUserName() + "</td>");
      sb.append("<td nowrap>" + user.getDescription() + "</td>");
      for (Task task : tasks) {
        sb.append("<td align=\"center\" width=\"100\">");
        sb.append( generateSelect(user, task, pMap, privLabels)+ "</td>");
      }
      sb.append("</tr>\n");
    }
    out.println(sb.toString());
  }
%>
</tbody>
<%
  if (users.size() > 20) { // show footer if too many entries
%>
<tfoot>
<%=printHeader(tasks)%>
</tfoot>
<%
  }
%>
</table>
<br>
<input id="msg_save" type="button" value=" SAVE " style="width:80px" onClick="save()">
<hr>
<h3>Privilege Legend - Actions Permitted for each role</h3>
<table cellpadding="0" cellspacing="0" border="0" class="datatable">
<thead>
<tr><th>Permitted Actions \ Roles</th><th>- (No Role)</th><th>Participant</th><th>Assessor</th><th>Organizer</th><th>Admin</th></tr>
</thead><tbody>
<tr class="odd"> <td>Search Corpus</td>        <td>No</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td></tr>
<tr class="even"><td>Upload/Download files</td><td>No</td><td>Yes</td><td>Yes</td><td>Yes</td><td>Yes</td></tr>
<tr class="odd"> <td>Develop Topics</td>       <td>No</td><td>No</td> <td>Yes</td><td>Yes</td><td>Yes</td></tr>
<tr class="even"><td>Do Evaluation</td>        <td>No</td><td>No</td> <td>Yes</td><td>Yes</td><td>Yes</td></tr>
<tr class="odd"> <td>Export Data</td>          <td>No</td><td>No</td> <td>Yes</td><td>Yes</td><td>Yes</td></tr>
<tr class="even"><td>Import/delete Data</td>   <td>No</td><td>No</td> <td>No</td> <td>Yes</td><td>Yes</td></tr>
<tr class="odd"> <td>Manage SEPIA</td>         <td>No</td><td>No</td> <td>No</td> <td>No</td> <td>Yes</td></tr>
</tbody>
</table>
<%
  out.println(Commons.getFooter(request, response));
%>

